package cn.jhc.teachingquality.net;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

import static cn.jhc.teachingquality.Global.LOG_TAG;
import static cn.jhc.teachingquality.Global.PREFERENCES;
import static cn.jhc.teachingquality.Global.PREF_PASSWORD;
import static cn.jhc.teachingquality.Global.PREF_USERNAME;
import static cn.jhc.teachingquality.Global.URL_PREFIX;

/**
 * Created by luyanfei on 16-3-8.
 */
public class LoginRequest extends StringRequest {

    private static final String LOGIN_URL = URL_PREFIX + "/loginAction!userLogin.shtml";

    private String username;
    private String password;

    public LoginRequest(String username, String password, Response.Listener<String> listener,
                        Response.ErrorListener errorListener) {
        super(Method.POST, LOGIN_URL, listener, errorListener);
        this.username = username;
        this.password = password;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        if(username == null || password == null
                || username.length() == 0 || password.length() == 0){
            throw new AuthFailureError("Username of password does not exists.");
        }
        Map<String, String> map = new HashMap<>();
        map.put("sysUser.userCode", username);
        map.put("sysUser.password", password);
        map.put("userCode", username);
        map.put("password", password);
        map.put("type", "JS");
        return map;
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        Response<String> origin = super.parseNetworkResponse(response);
        String cookieValue = response.headers.get("Set-Cookie");
        Log.d(LOG_TAG, "Set-Cookie received: " + cookieValue);
        return origin;
    }
}
